package com.gz.web.exception;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
public class MyExceptionHandler{

    //异常处理优先级:局部异常>全局异常>SimpleMappingExceptionResolver(xml文件中配置的异常处理)

    @ExceptionHandler({ArithmeticException.class,NullPointerException.class})
    public String localException(Exception ex, HttpServletRequest request){
        System.out.println("局部异常信息是: "+ex.getMessage());
        request.setAttribute("reason", ex);
        return "exception_mes";
    }

    //模拟异常 算数异常
    //如果我们不处理，就有tomcat默认页面处理，如500页面
    //如果出现异常，先照本类带有的 方法，然后处理异常
    @RequestMapping(value = "/testException01")
    public String test01(Integer num){ //测试局部异常
        int i=9/num;
        return "success";
    }

    @RequestMapping(value = "/testException02")
    public String global(){ //测试全局异常
        int i=Integer.parseInt("hello");
        return "success";
    }

    @RequestMapping(value = "/testException03")
    public String test03(){ //测试自定义异常
        throw new AgeException("年龄需要在1-120之间");
    }

    @RequestMapping(value = "/testException04")
    public String test04(){ //统一处理异常 (到xml文件中看配置)
        int[] arr=new int[]{1,2,3,4,5};
        //抛出一个数组越界异常
        System.out.println(arr[90]);
        return "success";
    }

    @RequestMapping(value = "/testException05")
    public String test05(){ //统一处理未知异常 (到xml文件中看配置)
        String str="hello";
        char ch=str.charAt(10);
        return "success";
    }
}
